/**
 * 认证相关工具函数
 */

// 重新定义用户角色，确保向后兼容
export enum UserRole {
  ADMIN = 'ADMIN',
  SCHOOL_ADMIN = 'SCHOOL_ADMIN',
  TEACHER = 'TEACHER',
  PARENT = 'PARENT'
}

// 用户状态
export enum UserStatus {
  ACTIVE = 'ACTIVE',
  SUSPENDED = 'SUSPENDED',
  INACTIVE = 'INACTIVE'
}

// 用户信息接口
export interface UserInfo {
  id: string
  username: string
  realName: string
  name?: string
  role: UserRole
  avatar?: string
  phone?: string
  email?: string
  status: UserStatus
  lastLoginTime?: string
  createdTime: string
  schoolId?: string
  permissions?: string[]
}

// 权限定义
export interface Permission {
  resource: string        // 资源标识
  actions: string[]       // 允许的操作
}

// 角色权限映射
const ROLE_PERMISSIONS: Record<UserRole, Permission[]> = {
  [UserRole.ADMIN]: [
    { resource: 'user', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'class', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'student', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'record', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'system', actions: ['read', 'update'] }
  ],
  [UserRole.SCHOOL_ADMIN]: [
    { resource: 'user', actions: ['read', 'update'] },
    { resource: 'class', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'student', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'record', actions: ['create', 'read', 'update', 'delete'] },
    { resource: 'system', actions: ['read'] }
  ],
  [UserRole.TEACHER]: [
    { resource: 'student', actions: ['create', 'read', 'update'] },
    { resource: 'record', actions: ['create', 'read', 'update', 'delete'] }
  ],
  [UserRole.PARENT]: [
    { resource: 'student', actions: ['read'] },
    { resource: 'record', actions: ['read'] }
  ]
}

// 登录凭据
export interface LoginCredentials {
  username: string
  password: string
}

// 登录响应
export interface LoginResponse {
  token: string
  refreshToken: string
  userInfo: UserInfo
  expiresIn: number
}

/**
 * 检查用户是否已登录
 */
export function isLoggedIn(): boolean {
  try {
    const token = uni.getStorageSync('auth_token')
    return !!token
  } catch (error) {
    console.error('检查登录状态失败:', error)
    return false
  }
}

/**
 * 获取当前用户信息
 */
export function getCurrentUser(): UserInfo | null {
  try {
    const userInfo = uni.getStorageSync('user_info')
    return userInfo ? JSON.parse(userInfo) : null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

/**
 * 获取当前用户角色
 */
export function getCurrentRole(): UserRole | null {
  const user = getCurrentUser()
  return user?.role || null
}

/**
 * 检查用户是否有指定权限
 */
export function hasPermission(resource: string, action: string): boolean {
  const user = getCurrentUser()
  if (!user) return false

  const permissions = user.permissions || ROLE_PERMISSIONS[user.role] || []
  return permissions.some(permission =>
    permission.resource === resource &&
    permission.actions.includes(action)
  )
}

/**
 * 检查用户是否可以访问指定页面
 */
export function canAccessPage(pagePath: string): boolean {
  const role = getCurrentRole()
  if (!role) return false

  // 页面权限映射
  const pagePermissions: Record<string, UserRole[]> = {
    '/pages/admin/dashboard': [UserRole.ADMIN, UserRole.SCHOOL_ADMIN],
    '/pages/admin/user-list': [UserRole.ADMIN, UserRole.SCHOOL_ADMIN],
    '/pages/admin/user-detail': [UserRole.ADMIN, UserRole.SCHOOL_ADMIN],
    '/pages/admin/class-manage': [UserRole.ADMIN, UserRole.SCHOOL_ADMIN],
    '/pages/admin/system-settings': [UserRole.ADMIN],
    '/pages/admin/logs': [UserRole.ADMIN, UserRole.SCHOOL_ADMIN],
    '/pages/teacher/dashboard': [UserRole.TEACHER],
    '/pages/teacher/student-list': [UserRole.TEACHER],
    '/pages/teacher/student-record': [UserRole.TEACHER],
    '/pages/teacher/excel-import': [UserRole.TEACHER],
    '/pages/parent/dashboard': [UserRole.PARENT],
    '/pages/parent/student-info': [UserRole.PARENT],
    '/pages/parent/record-view': [UserRole.PARENT]
  }

  return pagePermissions[pagePath]?.includes(role) || false
}

/**
 * 保存登录信息
 */
export function saveLoginInfo(token: string, refreshToken: string, userInfo: UserInfo, expiresIn: number): void {
  try {
    uni.setStorageSync('token', token)
    uni.setStorageSync('refreshToken', refreshToken)
    uni.setStorageSync('userInfo', JSON.stringify(userInfo))
    uni.setStorageSync('loginTime', Date.now())
    uni.setStorageSync('expiresIn', expiresIn)
  } catch (error) {
    console.error('保存登录信息失败:', error)
  }
}

/**
 * 清除登录信息
 */
export function clearLoginInfo(): void {
  try {
    uni.removeStorageSync('token')
    uni.removeStorageSync('refreshToken')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('loginTime')
    uni.removeStorageSync('expiresIn')
  } catch (error) {
    console.error('清除登录信息失败:', error)
  }
}

/**
 * 根据角色获取首页路径
 */
export function getHomePathByRole(role: UserRole): string {
  const homePaths: Record<UserRole, string> = {
    [UserRole.ADMIN]: '/pages/admin/dashboard',
    [UserRole.SCHOOL_ADMIN]: '/pages/admin/dashboard',
    [UserRole.TEACHER]: '/pages/teacher/dashboard',
    [UserRole.PARENT]: '/pages/parent/dashboard'
  }
  return homePaths[role] || '/pages/index/index'
}

/**
 * 获取角色显示名称
 */
export function getRoleDisplayName(role: UserRole): string {
  const roleNames: Record<UserRole, string> = {
    [UserRole.ADMIN]: '超级管理员',
    [UserRole.SCHOOL_ADMIN]: '学校管理员',
    [UserRole.TEACHER]: '班主任',
    [UserRole.PARENT]: '家长'
  }
  return roleNames[role] || '未知角色'
}

/**
 * 检查Token是否即将过期（提前5分钟检查）
 */
export function isTokenExpiringSoon(): boolean {
  try {
    const loginTime = uni.getStorageSync('loginTime')
    const expiresIn = uni.getStorageSync('expiresIn')

    if (!loginTime || !expiresIn) return true

    const currentTime = Date.now()
    const expireTime = loginTime + (expiresIn * 1000)
    const fiveMinutes = 5 * 60 * 1000

    return (expireTime - currentTime) <= fiveMinutes
  } catch (error) {
    console.error('检查Token过期状态失败:', error)
    return true
  }
}

/**
 * 刷新Token（这里需要根据实际API实现）
 */
export async function refreshToken(): Promise<boolean> {
  try {
    // TODO: 实现Token刷新逻辑
    // const response = await request.post('/api/auth/refresh')
    // if (response.success) {
    //   saveLoginInfo(response.data.token, response.data.userInfo)
    //   return true
    // }
    return false
  } catch (error) {
    console.error('刷新Token失败:', error)
    return false
  }
}